/*登录界面*/
import  React,{Component}   from 'react';
import  storage             from '../../util/Storage';
import md5 from 'js-md5';
import  configs             from '../../redux/action/common/configs';
import  {connect}           from 'react-redux';
import  { 
        Input,
        Icon,
        Form, 
        Button,
        Card,
        message}            from 'antd';
import  {sendLogin,
        getVerification,
}            from "../../redux/action/common/userhead";
import {Link}               from 'react-router-dom';
import  "./Login.less";


const   FormItem  =Form.Item;
const   baseUrl   =configs.baseUrl;
let     jwtDecode = require('jwt-decode');
let     timer;
React.Component.prototype.$md5 = md5

@connect(state=>({
        header:state.userHeader
    })
)

class Login extends Component{
    constructor(props){
        super(props);
        this.state={
            page:0 ,// 判断是否显示页面
            pageRl:false ,//判断是否为登录
            t:0,
            uuid:"", 
        }
    }

    componentDidMount(){
       this.getCaptcha();
       //设置定时器
       this.setTimer();
       this.setState({
           page:this.props.header.displaying
       })
    }

    /**
     * 获取验证码
     * @param {string} uuid
     */
    getCaptcha=()=>{
        this.props.dispatch(
            getVerification()
            )
            .then(()=>{
                if(this.props.header.Captcha!=undefined)
                {
                    this.setState({
                        picSource :this.props.header.Captcha.data.code,
                        uuid      :this.props.header.Captcha.data.uuid
                    })
                    storage.setStorage('uuid',this.props.header.Captcha.data.uuid);
                }
                else
                {
                    message.warning("验证码获取失败");
                }

        })
    }

    /**
     * 登录
     */
    toLogin=()=>{
        let apply=this.props.form.getFieldsValue();
        this.getCaptcha(null);
       
        if(apply.usernameL  ===''
        ||apply.passwordL   ===''
        ||apply.validationL ===''
        ||localStorage.uuid ==='')
        {
            message.warning('信息不能为空')
        }
        else{
            // 添加固定盐
            let salt ="1a2b3c4d";
            let str = ""+salt.charAt(0)+salt.charAt(2) 
            + apply.passwordL +salt.charAt(5) + salt.charAt(4); 
            console.log('str',str);
          //  md5加密
            let passw=md5(str);
           
            this.props.dispatch(sendLogin({
                email       :apply.userNameL,
                password    :passw,
                verifyUuid  :localStorage.uuid,
                verifyCode  :apply.validationL
            })).then(()=>{
               
            }
            );
        } 
    }

        /**
         * 设置定时器
         */
        setTimer() {
            if (timer) {
                clearTimeout(timer);
            }
            //设置定时器
            if (localStorage.token) {
                try {
                    //得到过期时间
                    let token = jwtDecode(localStorage.token);
                    let time =token.exp * 1000 - 7 * 60 * 1000 - Date.parse(new Date());   
                    timer = setTimeout(() => {
                        this.reGetToken();  
                    }, time);
                } catch (error) {
                    console.log('timer err');
                }
            }
        }
        
        /**
         * 刷新token
         */
        reGetToken=()=>{
                message.info('用户认证已过期，请重新登录。');
                this.loginOut();
        }
       /**
        * 退出登录
        */
        loginOut() {
            // 如果存在定时器，则使用clearTimeout清空。
            timer && clearTimeout(timer);
            Storage.clearStorage();
            window.location.reload();
        }

        closeWindow=()=>{
            window.location.href='/';
        }


    render(){
        const {getFieldDecorator}=this.props.form;//getFieldDecorator属性，要用Form.create创建
        const {picSource,uuid,notEmpL,notEmp,page} = this.state;
        const styleImg={ 
            cursor: 'pointer',
            width:100,
            height:30,
            paddingBottom:5
        }
        return(
            <div className='login-wrap'>
                <div className="login-content">
                         <Card>
                            <Form style={{width:350}}>
                                <div className="login-content-close" 
                                onClick={this.closeWindow}>
                                    <Icon type="close" />
                                </div>
                                <div className="login-content-head">欢迎登录语义分析平台</div>
                                <FormItem>
                                    {
                                        getFieldDecorator('userNameL',{//初始化
                                            initialValue:'',
                                            rules:[{
                                                required:true,
                                                message:'用户名不能为空'
                                            },
                                                {
                                                    //判断范围
                                                    min:1,max:20,
                                                    message:'长度不在范围内'
                                                },{
                                                    // pattern:/^\w+$/g,//正则//这种也行
                                                    pattern:new RegExp('^[a-z0-9A-Z]+[- | a-z0-9A-Z . _]+@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-z]{2,}$'),
                                                    message:'请填写正确的邮箱格式'
                                                }
                                            ]
                                        })(<Input prefix={<Icon type="user"/>} placeholder="请输入用户名" />)
                                    }
                                </FormItem>
                                <FormItem>
                                    {
                                        getFieldDecorator('passwordL',{
                                            initialValue:'',
                                            rules:[{
                                                pattern:new RegExp('^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$'),
                                                message:'密码至少包含 数字和英文，长度6-20'
                                            }]
                                        })( <Input.Password prefix={<Icon type="lock"/>} placeholder="请输入密码"/>)
                                    }
                                </FormItem>
                                <FormItem>
                                    {
                                        getFieldDecorator('validationL',{
                                            initialValue:'',
                                            rules:[]
                                        })( <Input 
                                            prefix={<Icon type="heart" />}  
                                            style={{width:220}} 
                                            placeholder="请输入验证码"/>)

                                    }
                                    <div style={{float:'right',marginRight:30} }>
                                        <img 
                                            src={picSource?`data:image/png;base64,${picSource}`:null}
                                            style={styleImg}
                                            onClick={()=>this.getCaptcha(localStorage.uuid)}
                                        />
                                        </div>
                                </FormItem>
                                <FormItem>
                                    <a href="#" style={{float:'left'}}>忘记密码?</a>
                                    <div style={{float:'right',color:"#1890FF",cursor:"pointer"}}>
                                        <Link to={"/register"}>去注册</Link>
                                    </div>
                                </FormItem>
                                <Button 
                                style={{width:300,marginLeft:25}}  
                                type="primary" 
                                onClick={this.toLogin}>
                                    登录
                                </Button>
                                <FormItem>
                                    <div></div>
                                    <div></div>
                                    <div></div>
                                </FormItem>
                            </Form>
                        </Card>
                </div>
               
            </div>
        )
    }
}

export default Form.create()( Login);